package com.aio.news;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;

import com.aidi.lib.TAInjectView;
import com.aio.news.category.fragment.CategoryFragment;
import com.aio.news.home.fragment.LatestFragment;
import com.aio.news.utils.AppConstance;
import com.aio.news.view.MainTabTextView;

public class MainActivity extends Activity implements OnClickListener {

	private List<BaseFragment> mFragments = new ArrayList<BaseFragment>();
	private FragmentManager mFragmentManager;

	@TAInjectView(id = R.id.main_bottom)
	private LinearLayout tabLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		AppConstance.SCREEN_WIDTH = getResources().getDisplayMetrics().widthPixels;
		AppConstance.SCREEN_HEIGHT = getResources().getDisplayMetrics().heightPixels;
		setContentView(R.layout.activity_main);
		AioApplication.getInjector().injectView(this);
		mFragmentManager = getFragmentManager();
		FragmentTransaction mTransaction = mFragmentManager.beginTransaction();
		LatestFragment latestFragment = new LatestFragment();
		mTransaction.add(R.id.content, latestFragment,
				LatestFragment.class.getName()).commit();
		mFragments.add(latestFragment);
		initTabClick();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.home:
			changeFragments(LatestFragment.class.getName());
			break;
		case R.id.category:
			changeFragments(CategoryFragment.class.getName());
			break;

		default:
			break;
		}
		changeSelectedTab(v.getId());
	}

	private void initTabClick() {
		for (int i = 0; i < tabLayout.getChildCount(); i++) {
			tabLayout.getChildAt(i).setOnClickListener(this);
		}
	}

	private void changeFragments(String tag) {
		FragmentTransaction mTransaction = mFragmentManager.beginTransaction();
		for (BaseFragment mFragment : mFragments) {
			if (mFragment.getTag().equals(tag)) {
				if (mFragment.isAdded()) {
					mTransaction.show(mFragment);
				}
			} else {
				mTransaction.hide(mFragment);
			}
		}
		if (mFragmentManager.findFragmentByTag(tag) == null) {
			BaseFragment mFragment = (BaseFragment) Fragment.instantiate(this,
					tag);
			mTransaction.add(R.id.content, mFragment, tag);
			mFragments.add(mFragment);
		}
		mTransaction.commit();
	}

	private void changeSelectedTab(int id) {
		for (int i = 0; i < tabLayout.getChildCount(); i++) {
			MainTabTextView child = (MainTabTextView) tabLayout.getChildAt(i);
			child.setSelected(child.getId() == id);
		}
	}
}
